package com.xhsj.user.sms.purchase.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.xhsj.user.hr.system.entity.TbGlobalUser;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.sms.base.BaseService;
import com.xhsj.user.sms.process.dto.StartProcessDto;
import com.xhsj.user.sms.process.entity.TbPurchaseProcessTask;
import com.xhsj.user.sms.process.service.TbPurchaseProcessTaskService;
import com.xhsj.user.sms.purchase.entity.*;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseTaskFileMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseTaskListMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseTaskMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseTaskUserMapper;
import com.xhsj.user.sms.purchase.query.SmsApprovalQuery;
import com.xhsj.user.sms.purchase.query.PurchaseApplyQuery;
import com.xhsj.user.sms.purchase.query.SaveTaskUserQuery;
import com.xhsj.user.sms.purchase.vo.FindApplyListVo;
import com.xhsj.user.sms.purchase.vo.PurchaseApplyQueryVo;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购任务表 服务实现类
 * </p>
 *
 * @author suxiaolin
 * @since 2020-05-25
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbPurchaseTask")
public class TbPurchaseTaskService extends BaseService<TbPurchaseTaskMapper, TbPurchaseTask> {
    @Autowired
    private TbPurchaseTaskMapper dao;

    @Autowired
    private TbPurchaseTaskFileMapper tbPurchaseTaskFileMapper;

    @Autowired
    private TbPurchaseApplyService tbPurchaseApplyService;

    @Autowired
    private TbPurchaseTaskListMapper tbPurchaseTaskListMapper;
    @Autowired
    private TbGlobalUserService tbGlobalUserService;
    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;
    @Autowired
    private TbPurchaseProcessTaskService tbPurchaseProcessTaskService;
    @Autowired
    private TbPurchaseOrderService tbPurchaseOrderService;

    //角色名称 采购经理
    @Value("${rolekeyname.purchaseManager}")
    private String purchaseManager;

    //角色名称 总经理
    @Value("${rolekeyname.generalManager}")
    private String generalManager;

    @Autowired
    private TbPurchaseTaskUserMapper tbPurchaseTaskUserMapper;

    @Autowired
    private TbPurchaseTaskUserService tbPurchaseTaskUserService;


    public IPage<FindApplyListVo> findApplyList(IPage<TbPurchaseTask> page, PurchaseApplyQuery purchaseApplyQuery) {
        IPage<FindApplyListVo> iPage = dao.findPurchaseTask(page, purchaseApplyQuery);
        List<FindApplyListVo> records = iPage.getRecords();
        for (FindApplyListVo record : records) {
            String userId = record.getUserId();
            if (StringUtils.isNotBlank(userId)) {
                TbGlobalUser user = tbGlobalUserService.getById(userId);
                record.setAuditor(user.getFullName());
            }

            String roleId = record.getRoleId();
            if (StringUtils.isNotBlank(roleId)) {
                List<TbGlobalUser> list = tbGlobalUserMapper.getUserListByRoleId(roleId);
                String collect = list.stream().map(tbGlobalUser -> tbGlobalUser.getFullName()).collect(Collectors.joining(","));
                record.setAuditor(collect);
            }

            String deptId = record.getDeptId();
            if (StringUtils.isNotBlank(deptId)) {
                List<TbGlobalUser> list = tbGlobalUserMapper.getUserListByDeptId(deptId);
                String collect = list.stream().map(tbGlobalUser -> tbGlobalUser.getFullName()).collect(Collectors.joining(","));
                record.setAuditor(collect);
            }
        }
        return iPage;
    }

    public boolean saveTask(TbPurchaseTask entity) throws Exception {

        //查询采购经理角色
        List<String> roleKeyNameList = new ArrayList<>();
        roleKeyNameList.add(purchaseManager);
        Set<String> roleIds = tbGlobalUserMapper.getRoleListByRoleKeyName(roleKeyNameList);
        if (roleIds == null || roleIds.size() == 0) {
            throw new Exception("采购经理角色不存在,请联系管理员添加相关人员");
        }
        String collect = roleIds.stream().collect(Collectors.joining(","));
        entity.setBelongRole(collect);
        // 保存采购任务
        this.savePurchaseTask(entity);

        if (entity.getSubmitStatus() == 2) {
            //流程
            StartProcessDto startProcessDto = new StartProcessDto();
            startProcessDto.setCreateBy(entity.getCreateBy());
            startProcessDto.setDataId(entity.getId());
            SmsApprovalQuery smsApprovalQuery = new SmsApprovalQuery();
//            String category = entity.getCategory();
//            if ("4".equals(category)) { // 量产物料
//                List<String> roleKeyNames = new ArrayList<>();
//                roleKeyNames.add(generalManager);
//                Set<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleKeyName(roleKeyNames);
//                if (roleListByRoleName == null || roleListByRoleName.size() == 0) {
//                    throw new Exception("下一节点审核角色不存在,请联系管理员添加相关角色");
//                }
//                startProcessDto.setRoleIds(roleListByRoleName);
//                startProcessDto.setStatus("13");
//                smsApprovalQuery.setRoleIds(roleListByRoleName);
//            } else {
                // 查询领导
            String leader = tbGlobalUserService.getLeaderByUserId(StringUtils.toLong(entity.getCreateBy()));
            if (StringUtils.isBlank(leader)) {
                throw new Exception("部门领导不存在,请联系管理员添加相关人员");
            }
            startProcessDto.setUserId(Arrays.asList(leader));
            startProcessDto.setStatus("0");
            smsApprovalQuery.setUserId(Arrays.asList(leader));
//            }

            String s = tbPurchaseProcessTaskService.startProcess(startProcessDto);
            entity.setNodeName(s);
            if (dao.updateById(entity) != 1) {
                throw new Exception("采购申请表保存节点失败");
            }
            smsApprovalQuery.setDataId(entity.getId());
            smsApprovalQuery.setCreateBy(entity.getCreateBy());
            tbPurchaseProcessTaskService.sendMessage(smsApprovalQuery);
        }
        return true;

    }

    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbPurchaseTask getById(Serializable id) {
        return super.getById(id);
    }

    @Override
    //@CacheEvict(cacheNames="TbPurchaseTask", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

    //@Cacheable(key = "#data",sync = true)
    public IPage<TbPurchaseTask> selectPage(Map<String, Object> data) {
        int currentPage = 1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage = (Integer) data.get("page");
        }
        int pageSize = 20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize = (Integer) data.get("size");
        }

        TbPurchaseTask entity = JSON.parseObject(JSON.toJSONString(data), TbPurchaseTask.class);
        Page<TbPurchaseTask> page = new Page(currentPage, pageSize);
        QueryWrapper<TbPurchaseTask> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

    @Override
    //@Cacheable(value = "TbPurchaseTask",sync = true)
    public List<TbPurchaseTask> selectAll() {
        return super.selectAll();
    }


    /**
     * 保存采购任务
     *
     * @author 苏小林
     * @date 2020/5/25 10:11
     * @param: dataId
     * @return: boolean
     */
    public boolean savePurchaseTask(TbPurchaseTask entity) throws Exception {
        if (StringUtils.isNotBlank(entity.getId())) {
            dao.delById(entity.getId());
            entity.setId(null);
        }

        if (StringUtils.isBlank(entity.getPurchaseNumber())) {
            String applyNewNum = tbPurchaseApplyService.getApplyNewNum(entity.getDeptId(), entity.getCategory());
            if (StringUtils.isBlank(applyNewNum)) {
                throw new Exception("采购申请编号失败");
            }
            entity.setPurchaseNumber(applyNewNum);
        }

        entity.setDealWithStatus("未处理");
        boolean save = super.save(entity);
        if (save) {
            List<TbPurchaseTaskFile> tbPurchaseApplyFileList = entity.getTbPurchaseApplyFileList();
            for (TbPurchaseTaskFile tbPurchaseTaskFile : tbPurchaseApplyFileList) {
                tbPurchaseTaskFile.setId(IdGen.uuid());
                tbPurchaseTaskFile.setPurchaseTaskId(entity.getId());
                tbPurchaseTaskFile.setCreateBy(entity.getCreateBy());
                tbPurchaseTaskFile.setCreateDate(new Date());
                tbPurchaseTaskFile.setUpdateBy(entity.getCreateBy());
                tbPurchaseTaskFile.setUpdateDate(new Date());
                int insert = tbPurchaseTaskFileMapper.insert(tbPurchaseTaskFile);
                if (insert == 0) {
                    log.error("保存出错");
                    throw new Exception("保存出错");
                }
            }

            List<TbPurchaseTaskList> tbPurchaseApplyList = entity.getTbPurchaseApplyList();
            for (TbPurchaseTaskList tbPurchaseTaskList : tbPurchaseApplyList) {
                tbPurchaseTaskList.setId(IdGen.uuid());
                tbPurchaseTaskList.setCreateBy(entity.getCreateBy());
                tbPurchaseTaskList.setCreateDate(new Date());
                tbPurchaseTaskList.setUpdateBy(entity.getCreateBy());
                tbPurchaseTaskList.setUpdateDate(new Date());
                tbPurchaseTaskList.setPurchaseTaskId(entity.getId());
                int insert = tbPurchaseTaskListMapper.insert(tbPurchaseTaskList);
                if (insert == 0) {
                    log.error("保存出错");
                    throw new Exception("保存出错");
                }
            }
        } else {
            log.error("保存出错");
            throw new Exception("保存出错");
        }
        return true;
    }

    public IPage<TbPurchaseTask> findPurchaseTaskList(Map<String, Object> data) {
        int currentPage = 1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage = (Integer) data.get("page");
        }
        int pageSize = 20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize = (Integer) data.get("size");
        }

        Object status = data.get("status");


        Page<TbPurchaseTask> page = new Page(currentPage, pageSize);
        String userId = String.valueOf(data.get("userId"));

        TbPurchaseTask tbPurchaseTask = StringUtils.toJavaBean(data, TbPurchaseTask.class);
        List<String> roleNames = tbGlobalUserMapper.getRoleKeyNamesByUserId(StringUtils.toLong(data.get("userId")));
        if (roleNames.contains(purchaseManager)) { // 包含采购经理
            return dao.queryPurchaseTaskList(page, String.valueOf(status), tbPurchaseTask);
        }

        return dao.findPurchaseTaskList(page, userId, String.valueOf(status), tbPurchaseTask);

    }

    @Transactional(rollbackFor = Exception.class)
    public boolean saveTaskUser(SaveTaskUserQuery saveTaskUserQuery) throws Exception {
        TbPurchaseTaskUser tbPurchaseTaskUser = StringUtils.toJavaBean(saveTaskUserQuery, TbPurchaseTaskUser.class);
        tbPurchaseTaskUser.setCreateDate(new Date());
        tbPurchaseTaskUser.setUpdateBy(saveTaskUserQuery.getCreateBy());
        tbPurchaseTaskUser.setUpdateDate(new Date());
        tbPurchaseTaskUser.setId(IdGen.uuid());
        int insert = tbPurchaseTaskUserMapper.insert(tbPurchaseTaskUser);
        if (insert > 0) {
            TbPurchaseTask tbPurchaseTask = new TbPurchaseTask();
            tbPurchaseTask.setId(saveTaskUserQuery.getPurchaseTaskId());
            tbPurchaseTask.setAssignUserName(saveTaskUserQuery.getFullName());
            boolean b = this.updateById(tbPurchaseTask);
            if (!b) {
                throw new Exception("修改出错");
            }
        }
        // 查询 f5676361f23534644c3aa8fe504563987 采购经理分配成员流程
        String nodeId = "f5676361f23534644c3aa8fe504563987";
        QueryWrapper<TbPurchaseProcessTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("data_id", saveTaskUserQuery.getPurchaseTaskId());
        queryWrapper.eq("node_id", nodeId);
        TbPurchaseProcessTask tbPurchaseProcessTask = tbPurchaseProcessTaskService.getOne(queryWrapper);
        if (tbPurchaseProcessTask != null) {
            SmsApprovalQuery smsApprovalQuery = new SmsApprovalQuery();
            smsApprovalQuery.setDataId(saveTaskUserQuery.getPurchaseTaskId());
            smsApprovalQuery.setProcessTaskId(tbPurchaseProcessTask.getId());
            smsApprovalQuery.setStatus(0);
            smsApprovalQuery.setNodeId(nodeId);
            smsApprovalQuery.setProposerId(tbPurchaseProcessTask.getProposerId());
            smsApprovalQuery.setCreateBy(saveTaskUserQuery.getCreateBy());
            smsApprovalQuery.setUserId(Arrays.asList(saveTaskUserQuery.getUserId()));
            smsApprovalQuery.setSubmitStatus(2);
            Map<String, Object> mapParam = StringUtils.toJavaBean(smsApprovalQuery, Map.class);

            try {
                tbPurchaseProcessTaskService.handleAudit(mapParam);
            } catch (Exception e) {
                log.error("添加流程出错:{}", e);
                throw new Exception("修改出错");
            }
        }
        return true;
    }

    public PurchaseApplyQueryVo getPurchaseTaskById(String id) {
        return dao.getPurchaseTaskById(id);
    }

    public TbPurchaseTask getPurchaseTaskInfoById(String id) {
        TbPurchaseTask tbPurchaseTask = dao.getPurchaseTaskInfoById(id);
        if (tbPurchaseTask != null) {

            HashMap<String, Object> taskListMap = Maps.newHashMap();
            taskListMap.put("purchase_task_id", id);
            List<TbPurchaseTaskList> tbPurchaseTaskLists = tbPurchaseTaskListMapper.selectByMap(taskListMap);
            tbPurchaseTask.setTbPurchaseApplyList(tbPurchaseTaskLists);

            List<TbPurchaseTaskFile> tbPurchaseTaskFiles = tbPurchaseTaskFileMapper.selectByMap(taskListMap);
            tbPurchaseTask.setTbPurchaseApplyFileList(tbPurchaseTaskFiles);

        }

        return tbPurchaseTask;

    }

    public void delContractInfoById(String id) {
        dao.delContractInfoById(id);
    }

    // 通过任务id查询子任务数量
    public int getSubTaskCountByTaskId(String id) {
        return dao.getSubTaskCountByTaskId(id);
    }

    // 删除采购任务
    public int delPurchaseTaskById(String id) throws Exception {
        int i = dao.delPurchaseTaskById(id);
        if (i > 0) {
            List<TbPurchaseOrder> list = tbPurchaseOrderService.getPurchaseOrderByTaskId(id);
            if (list != null && list.size() > 0) {
                int count = dao.delPurchaseOrderById(id);
                if (count == 0) {
                    log.error("删除采购订单相关数据失败,返回count=" + count);
                    throw new Exception("删除采购订单相关数据失败");
                }

            }
        }

        TbPurchaseTask tbPurchaseTask = new TbPurchaseTask();
        tbPurchaseTask.setId(id);
        tbPurchaseTask.setSubmitStatus(1);
        tbPurchaseTask.setNodeName("");
        int i1 = dao.updateById(tbPurchaseTask);
        if (i1 == 0) {
            log.error("删除采购订单相关数据失败,返回i1=" + i1);
            throw new Exception("删除采购订单相关数据失败");
        }

        return i;
    }

    public List<Object> findPurchaseUserInfo() {

        List<PurchaseUserInfo> list = dao.findPurchaseUserInfo();
        Set<String> collect = list.stream().map(purchaseUserInfo -> purchaseUserInfo.getUserId()).collect(Collectors.toSet());
        List<Object> result = Lists.newArrayList();
        for (String s : collect) {
            HashMap<Object, Object> userMap = Maps.newLinkedHashMap();
            HashSet<Object> objects = Sets.newHashSet();
            HashSet<Object> deptSet = Sets.newHashSet();
            for (PurchaseUserInfo purchaseUserInfo : list) {
                if (purchaseUserInfo.getUserId().equals(s)) {
                    userMap.put("userId",s);
                    userMap.put("fullName",purchaseUserInfo.getFullName());
                    userMap.put("leader",purchaseUserInfo.getLeader());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("roleId",purchaseUserInfo.getRoleId());
                    jsonObject.put("roleName",purchaseUserInfo.getRoleName());
                    jsonObject.put("roleKeyname",purchaseUserInfo.getRoleKeyname());
                    objects.add(jsonObject);

                    JSONObject dept = new JSONObject();
                    dept.put("deptId",purchaseUserInfo.getDepartmentId());
                    dept.put("deptName",purchaseUserInfo.getDeptName());
                    deptSet.add(dept);
                }
            }
            userMap.put("role",objects);
            userMap.put("dept",deptSet);
            result.add(userMap);
        }

        return result;
    }
}
